<template>
    <div class="register-page">
        <!-- 左侧背景图 -->
        <div class="register-bg">
            <div class="bg-overlay"></div>
            <div class="bg-content">
                <h2>加入旅行社区</h2>
                <p>与全球旅行者分享你的故事和经验</p>
            </div>
        </div>

        <!-- 右侧注册表单 -->
        <div class="register-form-container">
            <div class="form-wrapper">
                <!-- 顶部logo -->
                <div class="logo">
                    <i class="fas fa-plane"></i>
                    <span>TravelShare</span>
                </div>

                <!-- 欢迎标题 -->
                <h1 class="welcome-title">创建账户</h1>
                <p class="welcome-subtitle">开始你的旅行分享之旅</p>

                <!-- 注册表单 -->
                <form @submit.prevent="handleRegister" class="register-form">
                    <!-- 用户名 -->
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <div class="input-group">
                            <i class="fas fa-user"></i>
                            <input type="text" id="username" v-model="form.username" placeholder="输入用户名" required
                                @blur="validateUsername" />
                        </div>
                        <span class="error-message" v-if="errors.username">{{ errors.username }}</span>
                    </div>

                    <!-- 邮箱 -->
                    <div class="form-group">
                        <label for="email">电子邮箱</label>
                        <div class="input-group">
                            <i class="fas fa-envelope"></i>
                            <input type="email" id="email" v-model="form.email" placeholder="输入邮箱地址" required
                                @blur="validateEmail" />
                        </div>
                        <span class="error-message" v-if="errors.email">{{ errors.email }}</span>
                    </div>

                    <!-- 密码 -->
                    <div class="form-group">
                        <label for="password">密码</label>
                        <div class="input-group">
                            <i class="fas fa-lock"></i>
                            <input :type="showPassword ? 'text' : 'password'" id="password" v-model="form.password"
                                placeholder="输入密码" required @input="checkPasswordStrength" />
                            <i :class="['fas', showPassword ? 'fa-eye-slash' : 'fa-eye']"
                                @click="togglePasswordVisibility"></i>
                        </div>
                        <div class="password-strength">
                            <div class="strength-bar" :class="passwordStrength >= 1 ? 'active' : ''"></div>
                            <div class="strength-bar" :class="passwordStrength >= 2 ? 'active' : ''"></div>
                            <div class="strength-bar" :class="passwordStrength >= 3 ? 'active' : ''"></div>
                            <div class="strength-bar" :class="passwordStrength >= 4 ? 'active' : ''"></div>
                            <span class="strength-text">{{ passwordStrengthText }}</span>
                        </div>
                        <span class="error-message" v-if="errors.password">{{ errors.password }}</span>
                    </div>

                    <!-- 确认密码 -->
                    <div class="form-group">
                        <label for="confirmPassword">确认密码</label>
                        <div class="input-group">
                            <i class="fas fa-lock"></i>
                            <input :type="showConfirmPassword ? 'text' : 'password'" id="confirmPassword"
                                v-model="form.confirmPassword" placeholder="再次输入密码" required
                                @blur="validateConfirmPassword" />
                            <i :class="['fas', showConfirmPassword ? 'fa-eye-slash' : 'fa-eye']"
                                @click="toggleConfirmPasswordVisibility"></i>
                        </div>
                        <span class="error-message" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</span>
                    </div>

                    <!-- 用户协议 -->
                    <div class="form-group agreement">
                        <label class="agreement-label">
                            <input type="checkbox" v-model="form.agreed" />
                            <span>我已阅读并同意</span>
                            <router-link to="/terms">《用户协议》</router-link>
                            <span>和</span>
                            <router-link to="/privacy">《隐私政策》</router-link>
                        </label>
                        <span class="error-message" v-if="errors.agreed">{{ errors.agreed }}</span>
                    </div>

                    <!-- 注册按钮 -->
                    <button type="submit" class="register-btn" :disabled="isLoading || !isFormValid">
                        <span v-if="!isLoading">注册</span>
                        <span v-else class="loading">
                            <i class="fas fa-spinner fa-spin"></i> 注册中...
                        </span>
                    </button>

                    <!-- 已有账号 -->
                    <p class="login-link">
                        已有账号? <router-link to="/login">立即登录</router-link>
                    </p>
                </form>
            </div>
        </div>
    </div>
</template>

<script>
    import { ref, computed } from 'vue';
    import { useRouter } from 'vue-router';
    import { useAuthStore } from '@/stores/auth';

    export default {
        name: 'RegisterPage',
        setup() {
            const router = useRouter();
            const authStore = useAuthStore();

            // 表单数据
            const form = ref({
                username: '',
                email: '',
                password: '',
                confirmPassword: '',
                agreed: false
            });

            // 错误信息
            const errors = ref({
                username: '',
                email: '',
                password: '',
                confirmPassword: '',
                agreed: ''
            });

            // 状态
            const showPassword = ref(false);
            const showConfirmPassword = ref(false);
            const isLoading = ref(false);
            const passwordStrength = ref(0);
            const passwordStrengthText = ref('');

            // 密码强度检查
            const checkPasswordStrength = () => {
                const password = form.value.password;
                let strength = 0;

                // 长度检查
                if (password.length >= 8) strength++;
                // 包含数字
                if (/\d/.test(password)) strength++;
                // 包含小写字母
                if (/[a-z]/.test(password)) strength++;
                // 包含大写字母或特殊字符
                if (/[A-Z]/.test(password) || /[^A-Za-z0-9]/.test(password)) strength++;

                passwordStrength.value = strength;

                // 设置强度文本
                switch (strength) {
                    case 0:
                        passwordStrengthText.value = '';
                        break;
                    case 1:
                        passwordStrengthText.value = '非常弱';
                        break;
                    case 2:
                        passwordStrengthText.value = '弱';
                        break;
                    case 3:
                        passwordStrengthText.value = '中等';
                        break;
                    case 4:
                        passwordStrengthText.value = '强';
                        break;
                }
            };

            // 表单验证
            const validateUsername = () => {
                const username = form.value.username;
                if (!username) {
                    errors.value.username = '请输入用户名';
                } else if (username.length < 3) {
                    errors.value.username = '用户名至少3个字符';
                } else if (username.length > 20) {
                    errors.value.username = '用户名不能超过20个字符';
                } else {
                    errors.value.username = '';
                }
            };

            const validateEmail = () => {
                const email = form.value.email;
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

                if (!email) {
                    errors.value.email = '请输入邮箱地址';
                } else if (!emailRegex.test(email)) {
                    errors.value.email = '请输入有效的邮箱地址';
                } else {
                    errors.value.email = '';
                }
            };

            const validateConfirmPassword = () => {
                if (form.value.password !== form.value.confirmPassword) {
                    errors.value.confirmPassword = '两次输入的密码不一致';
                } else {
                    errors.value.confirmPassword = '';
                }
            };

            // 切换密码可见性
            const togglePasswordVisibility = () => {
                showPassword.value = !showPassword.value;
            };

            const toggleConfirmPasswordVisibility = () => {
                showConfirmPassword.value = !showConfirmPassword.value;
            };

            // 表单是否有效
            const isFormValid = computed(() => {
                return (
                    form.value.username &&
                    form.value.email &&
                    form.value.password &&
                    form.value.confirmPassword &&
                    form.value.agreed &&
                    !errors.value.username &&
                    !errors.value.email &&
                    !errors.value.password &&
                    !errors.value.confirmPassword
                );
            });

            // 处理注册
            const handleRegister = async () => {
                // 验证表单
                validateUsername();
                validateEmail();
                validateConfirmPassword();

                // 检查用户协议
                if (!form.value.agreed) {
                    errors.value.agreed = '请阅读并同意用户协议和隐私政策';
                    return;
                } else {
                    errors.value.agreed = '';
                }

                // 如果有错误，不提交
                if (Object.values(errors.value).some(error => error)) {
                    return;
                }

                isLoading.value = true;
                try {
                    await authStore.register({
                        username: form.value.username,
                        email: form.value.email,
                        password: form.value.password
                    });

                    // 注册成功后重定向
                    router.push('/');
                } catch (error) {
                    console.error('注册失败:', error);
                    // 处理错误，如邮箱已存在等
                    if (error.response && error.response.data.message) {
                        if (error.response.data.message.includes('email')) {
                            errors.value.email = error.response.data.message;
                        } else if (error.response.data.message.includes('username')) {
                            errors.value.username = error.response.data.message;
                        }
                    }
                } finally {
                    isLoading.value = false;
                }
            };

            return {
                form,
                errors,
                showPassword,
                showConfirmPassword,
                isLoading,
                passwordStrength,
                passwordStrengthText,
                isFormValid,
                validateUsername,
                validateEmail,
                validateConfirmPassword,
                togglePasswordVisibility,
                toggleConfirmPasswordVisibility,
                checkPasswordStrength,
                handleRegister
            };
        }
    };
</script>

<style scoped>
    /* 基础样式 */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    /* 注册页面布局 */
    .register-page {
        display: flex;
        min-height: 100vh;
    }

    /* 左侧背景 */
    .register-bg {
        flex: 1;
        background: url('https://images.unsplash.com/photo-1503220317375-aaad61436b1b?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80');
        background-size: cover;
        background-position: center;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
    }

    .bg-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.4);
    }

    .bg-content {
        position: relative;
        z-index: 1;
        padding: 40px;
        max-width: 600px;
    }

    .bg-content h2 {
        font-size: 36px;
        margin-bottom: 15px;
        line-height: 1.3;
    }

    .bg-content p {
        font-size: 18px;
        opacity: 0.9;
    }

    /* 右侧注册表单 */
    .register-form-container {
        width: 450px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 40px;
        background-color: #fff;
    }

    .form-wrapper {
        width: 100%;
        max-width: 400px;
    }

    /* logo样式 */
    .logo {
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        font-size: 24px;
        font-weight: bold;
        color: #4CAF50;
    }

    .logo i {
        margin-right: 10px;
        font-size: 28px;
    }

    /* 欢迎标题 */
    .welcome-title {
        font-size: 28px;
        margin-bottom: 8px;
        color: #333;
    }

    .welcome-subtitle {
        font-size: 16px;
        color: #666;
        margin-bottom: 30px;
    }

    /* 表单样式 */
    .register-form {
        width: 100%;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        font-weight: 500;
        color: #555;
    }

    .input-group {
        position: relative;
        display: flex;
        align-items: center;
    }

    .input-group i:first-child {
        position: absolute;
        left: 15px;
        color: #777;
    }

    .input-group i:last-child {
        position: absolute;
        right: 15px;
        color: #777;
        cursor: pointer;
    }

    .input-group input {
        width: 100%;
        padding: 12px 15px 12px 45px;
        border: 1px solid #ddd;
        border-radius: 8px;
        font-size: 16px;
        transition: border-color 0.3s;
    }

    .input-group input:focus {
        border-color: #4CAF50;
        outline: none;
    }

    /* 错误消息 */
    .error-message {
        display: block;
        margin-top: 5px;
        font-size: 12px;
        color: #ff5722;
    }

    /* 密码强度 */
    .password-strength {
        display: flex;
        align-items: center;
        gap: 5px;
        margin-top: 10px;
    }

    .strength-bar {
        flex: 1;
        height: 4px;
        background-color: #eee;
        border-radius: 2px;
        transition: background-color 0.3s;
    }

    .strength-bar.active {
        background-color: #4CAF50;
    }

    .strength-text {
        margin-left: 10px;
        font-size: 12px;
        color: #666;
    }

    /* 用户协议 */
    .agreement {
        margin-top: 25px;
    }

    .agreement-label {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #555;
        cursor: pointer;
    }

    .agreement-label input {
        margin-right: 8px;
        accent-color: #4CAF50;
    }

    .agreement-label a {
        color: #4CAF50;
        text-decoration: none;
        margin: 0 5px;
        transition: color 0.3s;
    }

    .agreement-label a:hover {
        color: #3d8b40;
    }

    /* 注册按钮 */
    .register-btn {
        width: 100%;
        padding: 14px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-top: 20px;
        margin-bottom: 25px;
    }

    .register-btn:hover:not(:disabled) {
        background-color: #3d8b40;
    }

    .register-btn:disabled {
        background-color: #a5d6a7;
        cursor: not-allowed;
        opacity: 0.7;
    }

    .loading i {
        margin-right: 8px;
    }

    /* 登录链接 */
    .login-link {
        text-align: center;
        font-size: 14px;
        color: #666;
    }

    .login-link a {
        color: #4CAF50;
        text-decoration: none;
        font-weight: 500;
        transition: color 0.3s;
    }

    .login-link a:hover {
        color: #3d8b40;
    }

    /* 响应式设计 */
    @media (max-width: 992px) {
        .register-bg {
            display: none;
        }

        .register-form-container {
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
        }
    }

    @media (max-width: 576px) {
        .register-form-container {
            padding: 20px;
        }

        .welcome-title {
            font-size: 24px;
        }

        .welcome-subtitle {
            font-size: 14px;
        }
    }
</style>